<template>
  <div class="AgentAdmin">
    <a-card>
      <a-form :form="form">
        <a-row :gutter="30">
          <a-col :span="8">
            <a-form-item
              label="代理商名称"
              :label-col="{ span: 6}"
              :wrapper-col="{ span: 16, offset: 1}"
            >
              <a-input placeholder="请输入" v-decorator="['agentName']" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="手机号码" :label-col="{ span: 6}" :wrapper-col="{ span: 16, offset: 1}">
              <a-input placeholder="请输入" v-decorator="['phone']" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="创建时间" :label-col="{ span: 6 }" :wrapper-col="{ span: 16,offset:1 }">
              <a-range-picker
                style="width: 100%"
                v-decorator="['rangeConfig']"
                show-time
                format="YYYY-MM-DD HH:mm:ss"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="30">
          <a-col :span="23" :style="{textAlign:'right'}">
            <a-button type="primary" @click="getfindPage($event)">查询</a-button>
            <a-button type="dashed" @click="listExport">导出</a-button>
            <a-button @click="handleReset()">重置</a-button>
          </a-col>
        </a-row>
      </a-form>
    </a-card>
    <a-card style="margin-top:2%">
      <a-button type="primary" icon="plus" @click="showModal">新建</a-button>
      <a-table
        :columns="columns"
        :dataSource="data"
        :rowKey="record => record.id"
        @change="handleTableChange"
        :pagination="pagination"
        style="margin-top:2%"
      >
        <template slot="Nohave" slot-scope="text,record">
          <span>{{record.hasDev==1?"有":"无"}}</span>
        </template>
        <template slot="operate" slot-scope="text">
          <span class="blue" @click="showEdit(text)">编辑</span>
          <span class="red" v-show="isLine" @click="showDeleteConfirm(text)">删除</span>
        </template>
      </a-table>
    </a-card>
    <a-modal title="编辑代理商" :visible="visibleEdit" @ok="handleEditOk" @cancel="handleEditCancel">
      <a-form :form="form">
        <a-form-item label="代理商名称" :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }">
          <a-input style="width: 100%" placeholder="请输入" v-decorator="['agentEditName']" />
        </a-form-item>
        <a-form-item label="是否参与分润" :label-col="{ span: 5 }">
          <a-radio-group v-decorator="['isShareProfit']">
            <a-radio :value="1" @click="isShare = true">是</a-radio>
            <a-radio :value="2" @click="isShare = false">否</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item
          label="分润比例"
          :label-col="{ span: 5 }"
          :wrapper-col="{ span: 12 }"
          v-show="isShare"
        >
          <a-input style="width: 100%" placeholder="请输入" v-decorator="['shareProfitRatio']" />
        </a-form-item>
        <p>说明：参与分润后，该代理商相关的所有设备产生的订单，会分得“订单金额x分润比例”的金额到厂商账户，请在与代理商签订好相关合同的情况下，再开启此功能，以避免不必要的纠纷。</p>
      </a-form>
    </a-modal>
    <a-modal
      title="新增代理商"
      :visible="visible"
      @ok="handleOk"
      @cancel="handleCancel"
      v-model="visible"
    >
      <template slot="footer">
        <a-button key="back" @click="handleCancel">取消</a-button>
        <a-button key="submit" type="primary" html-type="submit" @click="handleOk">确定</a-button>
      </template>
      <a-form :form="form">
        <a-form-item label="代理商名称" :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }">
          <a-input placeholder="请输入" v-decorator="['agentNamePop']" />
        </a-form-item>
        <a-form-item label="商品大类" :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }">
          <a-tree-select
            :treeData="treeData"
            v-decorator="['bigClass']"
            @change="onChange"
            treeCheckable
            placeholder="请选择"
          />
        </a-form-item>
        <a-form-item label="手机号码" :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }">
          <a-input v-model="phonePop" placeholder="请输入" />
        </a-form-item>
        <a-form-item label="登录账号" :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }">
          <span>{{phonePop}}</span>
        </a-form-item>
        <a-form-item label="初始密码" :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }">
          <span>0123456</span>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
import moment from "moment";

const treeData = [
  {
    title: "Node1",
    value: 1
  },
  {
    title: "Node2",
    value: 2
  }
];

const columns = [
  {
    title: "代理商名称",
    dataIndex: "name",
    key: "AgentName",
    scopedSlots: { customRender: "AgentName" },
    align: "center"
  },
  {
    title: "手机号码",
    dataIndex: "cellphone",
    key: "phone",
    scopedSlots: { customRender: "phone" },
    align: "center"
  },
  {
    title: "有无设备",
    dataIndex: "hasDev",
    key: "isFacility",
    scopedSlots: { customRender: "Nohave" },
    align: "center"
  },
  {
    title: "设备数",
    key: "facilityNum",
    dataIndex: "devNumber",
    scopedSlots: { customRender: "facilityNum" },
    align: "center"
  },
  {
    title: "分润比例",
    key: "profit",
    dataIndex: "distributionRate",
    scopedSlots: { customRender: "profit" },
    align: "center"
  },
  {
    title: "创建时间",
    dataIndex: "createTime",
    key: "createTime",
    scopedSlots: { customRender: "rangeConfig" },
    align: "center"
  },
  {
    title: "操作",
    dataIndex: "",
    key: "operate",
    scopedSlots: { customRender: "operate" },
    align: "center"
  }
];
export default {
  name: "AgentAdmin",
  data() {
    return {
      form: this.$form.createForm(this),
      dateFormat: "YYYY/MM/DD",
      monthFormat: "YYYY/MM",
      data: [],
      columns,
      visible: false,
      visibleEdit: false,
      isShare: false,
      isLine: true,
      pagination: {
        showSizeChanger: true,
        showQuickJumper: true,
        pageSizeOptions: ["10", "20", "30", "40"], //每页条数选择器
        showTotal: (total, range) => {
          return `${range[0]}-${range[1]} 共${total}条`;
        }, // 总数展示
        pageSize: 10, //每页条数
        defaultCurrent: 1, //默认当前页
        current: 1, //当前页
        total: 50 //数据总条数
      },
      phonePop: "",
      treeData: []
    };
  },
  methods: {
    onChange(value) {
      console.log("onChange ", value);
      this.value = value;
    },
    handleReset() {
      this.form.resetFields();
      this.startTime = "";
      this.endTime = "";
    },
    showEdit(text) {
      this.visibleEdit = true;
      this.editId = text.id;
      this.editInit(this.editId);
    },
    handleEditOk(e) {
      this.visibleEdit = false;
      this.edit(this.editId);
    },
    handleEditCancel(e) {
      this.visibleEdit = false;
    },
    showModal() {
      this.visible = true;
      this.addInit();
    },

    handleOk(e) {
      if (this.phonePop.length == 11 && !isNaN(this.phonePop)) {
        this.visible = false;
        this.listSave();
      } else {
        this.$message.warning("请输入正确的手机号");
      }
    },
    handleCancel(e) {
      this.visible = false;
    },
    // 删除确认弹框
    showDeleteConfirm(text) {
      var that = this;
      this.delId = text.id;
      this.$confirm({
        title: "确认删除？",
        content: "确认要删除吗",
        okText: "确定",
        cancelText: "取消",
        iconType: "close-circle",
        onOk() {
          that.del(that.delId);
          console.log("OK");
        },
        onCancel() {
          console.log("Cancel");
        }
      });
    },
    handleTableChange(pagination, filters, sorter) {
      const pager = { ...this.pagination };
      pager.current = pagination.current;
      pager.pageSize = pagination.pageSize;
      pager.total = pagination.total;
      this.pagination = pager;

      this.getfindPage();
    },
    // 列表初始化
    listInit() {
      this.axios
        .post(this.baseUrl + "/agent/listInit", {
          loginToken: this.$store.state.loginToken
        })
        .then(response => {
          // console.log(response);
        });
    },
    // 展示查询数据
    getfindPage($event) {
      if ($event) {
        this.pagination.current = 1;
      }
      var values = this.form.getFieldsValue();
      if (values.rangeConfig == undefined) {
        values.rangeConfig == undefined;
      } else {
        this.startTime = moment(values.rangeConfig[0]._d).format(
          "YYYY-MM-DD HH:mm:ss"
        );
        this.endTime = moment(values.rangeConfig[1]._d).format(
          "YYYY-MM-DD HH:mm:ss"
        );
      }
      this.axios
        .post(this.baseUrl + "/agent/list", {
          pageNum: this.pagination.current,
          pageSize: this.pagination.pageSize,
          cellphone: values.phone,
          startCreateTime: this.startTime,
          endCreateTime: this.endTime,
          havaDevice: values.isFacility,
          name: values.agentName,
          loginToken: this.$store.state.loginToken
        })
        .then(response => {
          console.log(response);
          this.data = response.data.data.list;
          this.pagination.total = response.data.data.total;
          this.pagination.pageSize = response.data.data.pageSize;
          this.pagination.current = response.data.data.pageNum;
        });
    },
    // 新增代理商初始化
    addInit() {
      this.axios
        .post(this.baseUrl + "/agent/addInit", {
          loginToken: this.$store.state.loginToken
        })
        .then(response => {
          console.log(response);
          this.classifyList = response.data.data;
          this.treeData = this.classifyList.map((item, index, arr) => {
            return { title: item.name, value: item.id };
          });
        });
    },
    // 新增代理商
    listSave() {
      var values = this.form.getFieldsValue();
      this.axios
        .post(this.baseUrl + "/agent/save", {
          loginToken: this.$store.state.loginToken,
          name: values.agentNamePop,
          cellphone: this.phonePop,
          catId: String(values.bigClass)
        })
        .then(response => {
          console.log(response);
          if (response.data.code == 0) {
            this.$message.info("新增代理商成功");
            this.getfindPage();
          }
        });
    },
    // 编辑代理商初始化
    editInit(id) {
      this.axios
        .post(this.baseUrl + "/agent/editInit", {
          id: id,
          loginToken: this.$store.state.loginToken
        })
        .then(response => {
          console.log(response);
          var isShareProfit = response.data.data.distributionRate;
          var agentEditName = response.data.data.name;
          this.form.setFieldsValue({
            shareProfitRatio: isShareProfit,
            agentEditName: agentEditName
          });
        });
    },
    // 编辑代理商
    edit(id) {
      var values = this.form.getFieldsValue();
      this.axios
        .post(this.baseUrl + "/agent/edit", {
          distributionRate:
            values.isShareProfit == 2 ? "0" : values.shareProfitRatio,
          name: values.agentEditName,
          id: id,
          loginToken: this.$store.state.loginToken
        })
        .then(response => {
          console.log(response);
          if (response.data.code == 0) {
            this.$message.info("编辑代理商成功");
            this.getfindPage();
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    // 删除商品
    del(id) {
      this.axios
        .post(this.baseUrl + "/agent/del", {
          id: id,
          loginToken: this.$store.state.loginToken
        })
        .then(response => {
          this.getfindPage();
          console.log(response);
        })
        .catch(error => {
          console.log(error);
        });
    },
    // 导出商品列表
    listExport() {
      var values = this.form.getFieldsValue();
      if (values.creationTime == undefined) {
        values.creationTime == undefined;
      } else {
        this.startCreateTime = moment(values.creationTime[0]._d).format(
          "YYYY-MM-DD HH:mm:ss"
        );
        this.endCreateTime = moment(values.creationTime[1]._d).format(
          "YYYY-MM-DD HH:mm:ss"
        );
      }
      this.axios
        .post(
          this.baseUrl + "/agent/export",
          {
            cellphone: values.phone,
            havaDevice: values.isFacility,
            startCreateTime: this.startCreateTime,
            endCreateTime: this.endCreateTime,
            name: values.agentName,
            loginToken: this.$store.state.loginToken
          },
          { responseType: "arraybuffer" }
        )
        .then(response => {
          console.log(response);
          if (response.status == "200") {
            const aLink = document.createElement("a");
            let blob = new Blob([response.data], {
              type: "application/vnd.ms-excel"
            });
            aLink.href = URL.createObjectURL(blob);
            aLink.download = "代理商管理表";
            aLink.click();
            document.body.appendChild(aLink);
          }
        })
        .catch(error => {
          // console.log(error);
        });
    }
  },
  created() {
    this.listInit();
    this.getfindPage();
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.AgentAdmin {
  width: 100%;
}
.ant-btn-primary,
.ant-btn-dashed {
  margin-right: 10px;
}
</style>
